package com.aiti.lulian.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.framework.commons.dictmodel.entity.SysDictData;
import com.aiti.framework.commons.dictmodel.mapper.SysDictDataMapper;
import com.aiti.lulian.gxmh.dto.*;
import com.aiti.lulian.gxmh.excel.GxmhExcelArticleListener;
import com.aiti.lulian.gxmh.excel.GxmhExcelArticleParamDto;
import com.aiti.lulian.gxmh.excel.GxmhExportArticleVo;
import com.aiti.lulian.gxmh.service.GovArticleManageService;
import com.aiti.lulian.gxmh.service.GxmhCustomizeFormService;
import com.aiti.lulian.gxmh.service.GxmhCustomizeFormTypeService;
import com.aiti.lulian.gxmh.vo.*;
import com.aiti.lulian.mapper.SysAreaMapper;
import com.aiti.lulian.mapper.gxmh.GxmhPolicyVisitMapper;
import com.aiti.lulian.service.GxmhPolicyVisitService;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * description:
 * auth fcb
 * date 2025-06-18 09:07
 **/
@RestController
@RequestMapping("/gxmh/policyManage")
@Api(tags = "工信门户政策管理系统")
@Slf4j
public class GxmhPolicyManageController extends WebController {

    @Autowired
    private GovArticleManageService govArticleManageService;
    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private GxmhCustomizeFormService gxmhCustomizeFormService;
    @Autowired
    private GxmhCustomizeFormTypeService gxmhCustomizeFormTypeService;
    @Autowired
    private GxmhPolicyVisitService gxmhPolicyVisitService;
    @Autowired
    private GxmhPolicyVisitMapper gxmhPolicyVisitMapper;


    @PostMapping("/saveArticle")
    @ApiOperation("保存文章")
    public Message saveArticle(@RequestBody GxmhArticleParamDto dto) {
        try {
            govArticleManageService.saveArticle(dto, findUserId());
            return Message.success();
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("保存文章异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/updateArticle")
    @ApiOperation("更新文章")
    public Message updateArticle(@RequestBody GxmhArticleParamDto dto) {
        try {
            govArticleManageService.updateArticle(dto, findUserId());
            return Message.success();
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("更新文章异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @GetMapping("/getArticleByBaseId")
    @ApiOperation("查询文章")
    public Message getArticleByBaseId(@RequestParam("baseId") String baseId) {
        try {
            GxmhArticleVo dto = govArticleManageService.queryArticleByBaseId(baseId);
            return Message.success(dto);
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("查询文章异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/removeArticle")
    @ApiOperation("删除文章")
    public Message removeArticle(@RequestBody List<String> list) {
        try {
            govArticleManageService.removeByBaseIdList(list);
            return Message.success();
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("删除文章异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/queryArticleList")
    @ApiOperation("查询政策列表")
    public Message queryArticleList(@RequestBody GxmhArticleQueryParamDto dto) {
        try {
            PageResult<GxmhArticleVo> pageResult = govArticleManageService.queryArticleList(dto, findUserId());
            return Message.success(pageResult);
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("查询文章列表异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @GetMapping("/downloadTemplateExcel")
    @ApiOperation(value = "下载模板")
    public void downloadTemplateExcel(HttpServletResponse response) {
        try {
            Resource resource = new ClassPathResource("file/政策导入模板.xlsx");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode("政策导入模板.xlsx", "UTF-8"));
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            IOUtils.copy(resource.getInputStream(), response.getOutputStream());
        }catch (Exception e) {
            log.error("【下载模板异常】：{}", ExceptionUtil.stacktraceToString(e));
        }
    }

    @PostMapping("/import")
    @ApiOperation(value = "导入政策")
    public Message importWorkFormExcel(@RequestParam("file") MultipartFile file) {
        if(file.isEmpty()) {
            return Message.fail("文件为空");
        }
        if(!"xlsx".equalsIgnoreCase(FileUtil.getSuffix(file.getOriginalFilename()))) {
            return Message.fail("文件格式错误");
        }
        try {
            String createUserId = findUserId();
            List<SysDictData> policyTypeList = govArticleManageService.queryPolicyTypeList();
            GxmhExcelArticleListener listener = new GxmhExcelArticleListener(govArticleManageService, createUserId, transactionManager, sysAreaMapper, policyTypeList);
            EasyExcel.read(file.getInputStream(), GxmhExcelArticleParamDto.class, listener).sheet().doRead();
            return Message.success("导入成功");
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("【政策导入异常】：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("导入失败");
        }
    }

    @GetMapping("/export")
    @ApiOperation(value = "导出政策")
    public void export( GxmhArticleQueryParamDto dto, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("政策", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), GxmhExportArticleVo.class).sheet("政策").doWrite(govArticleManageService.getAllData(dto, this.findUserId()));
        }catch (Exception e) {
            log.error("【导出异常】：{}", ExceptionUtil.stacktraceToString(e));
            try {
                IOUtils.write("导出失败", response.getOutputStream());
            } catch (IOException e1) {
                log.error("【导出异常1】：{}", ExceptionUtil.stacktraceToString(e1));
            }

        }
    }

    @GetMapping("/exportVisit")
    @ApiOperation(value = "导出政策访问")
    public void exportPolicyVisit(GxmhPolicyVisitParamDto queryDto, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("政策访问", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), GxmhPolicyVisitVo.class).sheet("政策访问").doWrite(gxmhPolicyVisitMapper.queryPolicyVisitList(null, queryDto));
        }catch (Exception e) {
            log.error("【导出异常】：{}", ExceptionUtil.stacktraceToString(e));
            try {
                IOUtils.write("导出失败", response.getOutputStream());
            } catch (IOException e1) {
                log.error("【导出异常1】：{}", ExceptionUtil.stacktraceToString(e1));
            }

        }
    }

    @PostMapping("/queryPolicyVisitList")
    @ApiOperation(value = "查询政策访问记录")
    public Message queryPolicyVisitList(@RequestBody GxmhPolicyVisitParamDto queryDto) {
        try {
            PageResult<GxmhPolicyVisitVo> gxmhPolicyVoPageResult = gxmhPolicyVisitService.queryPolicyVisitList(queryDto);
            return Success(gxmhPolicyVoPageResult);
        }catch (Exception e) {
            log.error("查询政策访问记录失败：{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("接口异常：" + e.getMessage());
        }
    }

    @GetMapping("/queryUserArea")
    @ApiOperation("查询用户区域")
    public Message queryUserArea() {
        try {
            GxmhUserAreaVo dto = govArticleManageService.queryUserArea(findUserId());
            return Message.success(dto);
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("查询用户区域异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/queryPolicyDeclareList")
    @ApiOperation("查询申报政策列表")
    public Message queryPolicyDeclareList(@RequestBody GxmhPolicyDeclareQueryDto queryDto) {
        try {
            PageResult<GxmhPolicyDeclareListItemVo> pageResult = govArticleManageService.queryPolicyDeclareList(queryDto, findUserId());
            return Message.success(pageResult);
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("查询政策列表异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/queryFormDeclareList")
    @ApiOperation("查询申报政策列表")
    public Message queryFormDeclareList(@RequestBody GxmhPolicyDeclareQueryDto queryDto) {
        try {
            PageResult<GxmhFormDeclareVo> pageResult = govArticleManageService.queryFormDeclareList(queryDto, findUserId());
            return Message.success(pageResult);
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("查询政策列表异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/removePolicyDeclareByBaseIdList")
    @ApiOperation("删除申报政策")
    public Message removePolicyDeclareByBaseIdList(@RequestBody List<String> baseIdList) {
        try {
            govArticleManageService.removePolicyDeclareByBaseIdList(baseIdList);
            return Message.success();
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("删除申报政策异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @GetMapping("/exportPolicyDecalre")
    @ApiOperation(value = "导出政策申报")
    public void exportPolicyDecalre( GxmhPolicyDeclareQueryDto dto, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("政策申报", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), GxmhPolicyDeclareListItemVo.class).sheet("政策申报").doWrite(govArticleManageService.getPolicyDeclareList(dto, this.findUserId()));
        }catch (Exception e) {
            log.error("【导出异常】：{}", ExceptionUtil.stacktraceToString(e));
            try {
                IOUtils.write("导出失败", response.getOutputStream());
            } catch (IOException e1) {
                log.error("【导出异常1】：{}", ExceptionUtil.stacktraceToString(e1));
            }

        }
    }

    //------------------------------------------------自定义表单管理-----------------------------------------------

    @PostMapping("/addCustomizeFormType")
    @ApiOperation("添加自定义表单类型")
    public Message addCustomizeFormType(@RequestBody GxmhFormTypeDto dto) {
       try {
           GxmhCustomizeFormTypeVo typeVo = gxmhCustomizeFormTypeService.addFormType(dto, findUserId());
           return Message.success(typeVo);
       }catch (Exception e) {
           if(e instanceof BusinessException) {
               return Message.fail(e.getMessage());
           }
           log.error("添加异常：{}", ExceptionUtil.stacktraceToString(e));
           return Message.fail("接口异常："+ e.getMessage());
       }
    }

    @GetMapping("/getTypeOrFormList")
    @ApiOperation("获取表单类型列表或表单列表")
    public Message getTypeOrFormList(@RequestParam("type")String  type,
                                     @RequestParam(value = "parentId", required = false) String parentId) {
        try {
            List<GxmhAbstractItemVo> resultList = gxmhCustomizeFormTypeService.getListByType(type, parentId, findUserId());
            return Message.success(resultList);
        } catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("查询表单类型异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/customizeFormList")
    @ApiOperation("自定义表单列表")
    public Message customizeFormList(@RequestBody GxmhCustomizeFormQueryDto queryDto) {
        try {
            PageResult<GxmhCustomizeFormVo> pageResult = gxmhCustomizeFormService.getFormPageList(queryDto, findUserId());
            return Message.success(pageResult);
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("查询自定义表单列表异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/addCustomizeForm")
    @ApiOperation("添加自定义表单")
    public Message addCustomizeForm(@RequestBody GxmhFormDto dto) {
        try {
            gxmhCustomizeFormService.addCustomizeForm(dto, findUserId());
            return Message.success();
        } catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("添加自定义表单异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @GetMapping("/getFromDetail")
    @ApiOperation("获取自定义表单详情")
    public Message getFromDetail(@RequestParam(value = "formId") String formId) {
        try {
            return Message.success(gxmhCustomizeFormService.getFromDetail(formId));
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("查询异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping("/updateCustomizeForm")
    @ApiOperation("更新自定义表单")
    public Message updateCustomizeForm(@RequestBody GxmhFormDto dto) {
        try {
            gxmhCustomizeFormService.updateCustomizeForm(dto, findUserId());
            return Message.success();
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("更新异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @DeleteMapping("/removeCustomizeForm")
    @ApiOperation("删除自定义表单")
    public Message removeCustomizeForm(@RequestParam("formId") String formId) {
        try {
            gxmhCustomizeFormService.deleteCustomizeForm(formId);
            return Message.success();
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("删除异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常：" + e.getMessage());
        }
    }


}
